/**
 * http://usejsdoc.org/
 */
var http = require('http'),
	fs = require('fs'),
	url = require('url'),
	res,
	util = require('util'),
	staticModule = require('./static_module'),
	formidable = require('formidable'),
	jade = require('jade'),
	BASE_DIR = __dirname;

function render(res,template,options){
	var str = fs.readFileSync(template, 'utf8');
	var fn = jade.compile(str,{filename:template,pretty:true});
	var page = fn(options);
	res.writeHead( 200 , {"Content-Type":"text/html"});
	res.end(page);
}

/**
 * 创建首页函数
 * @param res http响应对象
 * @returns
 */
function defaultIndex(res){
	render(res,'index.jade',{'user':'devintam'});
}

/**
 * 创建show函数
 * @param res http响应对象
 * @returns
 */
function show(res){
	var realPath = BASE_DIR + '/'+ url.parse('show.html').pathname;
	var indexPage = fs.readFileSync(realPath);
	res.writeHead( 200 , {"Content-Type":"text/html"});
	res.end(indexPage);
}


/**
 * 创建上传图片函数
 * @param res http响应对象
 * @param req http请求对象
 */
function upload(res,req){
	var timestamp = Date.parse(new Date());
	/**创建formidable表单*/
	var form = new formidable.IncomingForm();
	form.parse(req, function(error,fields,files) {//解析post数据
		//window环境下，存在跨分区问题,需要使用下面这种方式
		//fs.renameSync(files.image.path, BASE_DIR+'/static/uploadFile/test.jpg');
		var fileName = timestamp + '_'+files.image.name;
		var readStream = fs.createReadStream(files.image.path);
		var writeStream = fs.createWriteStream(BASE_DIR+'/static/uploadFile/'+fileName);
		
		/**util.pump 和readStream.pipe 用法一样，前者已过时*/
		util.pump(readStream, writeStream, function(){
			fs.unlinkSync(files.image.path);
		});
//		readStream.pipe(res);
		render(res,'show_image.jade',{'imgUrl':"/uploadFile/"+fileName});
	});
}

/**创建http服务器*/
http.createServer(function(req,res){
	/**web客户端请求*/
	var pathname = url.parse(req.url).pathname;//获取url请求路径
	var realPath = BASE_DIR +'/static'+ pathname;
	switch (pathname) {
		case '/upload':upload(res, req);
			break;
		case '/':defaultIndex(res, req);
			break;
		case '/index':defaultIndex(res, req);
			break;
		case '/show':show(res);
			break;
		default: staticModule.getStaticFile(pathname,res,req);
			break;
	}
}).listen(8080,'127.0.0.1');

console.log('Server running at http://127.0.0.1:8080');